package com.naiterui.ehp.bs.im.service.message.push;

import org.springframework.stereotype.Service;

import com.naiterui.ehp.bs.im.network.protocl.Disturb;
import com.naiterui.ehp.bs.im.repository.mongo.DisturbDao;
import com.naiterui.ehp.bs.im.utils.DateUtils;
import com.naiterui.ehp.bs.im.vo.DisturbVO;

@Service
public class DisturbHandler {

    /**
     * 1，打开勿扰模式
     */
    private static final int DISTURB_ON = 1;

    private final DisturbDao disturbDao;

    public DisturbHandler(DisturbDao disturbDao) {
        this.disturbDao = disturbDao;
    }

    /**
     * 打开或关闭勿扰模式
     */
    public void setDisturb(Disturb disturb, int operate) {
        if (operate == DISTURB_ON) {
            disturbDao.saveOrModify(disturb);
        } else {
            disturbDao.removeDisturb(disturb.getUserId());
        }
    }

    /**
     * 获取勿扰 模式
     */
    public DisturbVO getDisturb(Long userId) {

        return disturbDao.findDisturb(userId);
    }

    /**
     * 判断用户是否 开启了 勿扰模式
     */
    public boolean isDisturb(Long userId) {
        DisturbVO disturb = disturbDao.findDisturb(userId);
        if (disturb != null && disturb.getBeginTime() != null && disturb.getEndTime() != null) {
            String beginTime = disturb.getBeginTime();
            String endTime = disturb.getEndTime();
            String currTime = DateUtils.formatDate("HH:mm");

            // 对比开始时间和 结束时间
            int greater = endTime.compareTo(beginTime);

            // 如果结束时间大于 开始时间
            if (greater > 0) {
                if (currTime.compareTo(beginTime) > 0 && currTime.compareTo(endTime) < 0) {
                    return true;
                }
                // 如果 结束 时间小雨开始时间
            } else if (greater < 0) {
                if (currTime.compareTo(beginTime) > 0 || currTime.compareTo(endTime) < 0) {
                    return true;
                }
            } else {
                return true;
            }
        }
        return false;
    }

}
